//
//  ZNWBNetworkManager.swift
//  ZNWeibo
//
//  Created by FunctionMaker on 2017/8/4.
//  Copyright © 2017年 FunctionMaker. All rights reserved.
//

import UIKit
import AFNetworking

enum ZNWBNetworkMethod {
    case GET
    case POST
}

class ZNWBNetworkManager: AFHTTPSessionManager {
    
    lazy var userAccount = ZNWBUserCount()
    
    var isLogin: Bool {
        return userAccount.access_token != nil
    }
    
    //单例的网络管理：静态/常量/闭包
    static let shared: ZNWBNetworkManager = {
        let result = ZNWBNetworkManager()
        // 增加可接受的内容格式，AFN默认支持三种
        result.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return result
    }()
    
    func tokenRequest(method: ZNWBNetworkMethod = .GET, URLString: String, parameters: [String: Any]?, completion:@escaping(_ json: Any?, _ isSuccessful: Bool)->Void) {
        
        // 程序运行期间，token不会为nil
        guard let token = userAccount.access_token
            
        else {
            // token为nil时才会重新登录
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: ZNWBLoginNotification), object: nil)
            
            completion(nil, false)
            
            return
        }
        
        var param = parameters
        
        if param == nil {
            param = [String: Any]()
        }
        
        param!["access_token"] = token
        
        request(URLString: URLString, parameters: param!, completion: completion)
    }
    
    func request(method: ZNWBNetworkMethod = .GET, URLString: String, parameters: [String: Any], completion:@escaping(_ json: Any?, _ isSuccessful: Bool)->Void) {
        let success = { (task: URLSessionDataTask?, json: Any?) -> () in
            completion(json, true)
        }
        
        let failure = { (task: URLSessionDataTask?, error: Error) -> () in
            print("网络请求错误:\(error.localizedDescription)")
            
            //判断Token是否过期，即HTTP状态码为403（禁止访问）
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: ZNWBLoginNotification), object: "do something")
            }
            
            completion(nil, false)
        }
        
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
             post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
}
